import { i18n } from '@/plugins/vueI18n'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { setHtmlPageLang } from '@/plugins/vueI18n/helper'
import { useAppStoreWithOut } from '@/store/modules/app'

const localeStore = useLocaleStoreWithOut()

const setI18nLanguage = (lang: LocaleType) => {
  // 如果是Vue选项式API
  if (i18n.mode === 'legacy') {
    i18n.global.locale = lang
  } else {
    ;(i18n.global.locale as any).value = lang
  }

  setHtmlPageLang(lang)

  const currentLocale =
    localeStore.localeMap.find((item) => item.lang === lang) || localeStore.localeMap[0]

  localeStore.setCurrentLocale(currentLocale)

  location.reload()
}

export const useLocale = () => {
  // Switching the language will change the locale of useI18n
  // And submit to configuration modification

  const changeLocale = async (lang: LocaleType) => {
    if (lang === localeStore.currentLocale.lang) {
      return
    }

    const globalI18n = i18n.global

    const appStore = useAppStoreWithOut()

    appStore.setPageLoading(true)

    const langModule = await import(`../../locales/${lang}.ts`)

    globalI18n.setLocaleMessage(lang, langModule.default)

    setI18nLanguage(lang)

    appStore.setPageLoading(false)
  }

  return {
    changeLocale
  }
}
